package com.corpgovernment.common.util;

import com.alibaba.fastjson.JSONObject;
import com.corpgovernment.common.enums.LogLevelEnum;
import com.ctrip.corp.obt.generic.core.ttl.Ttl;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @program: corp-mobile-api-application
 * @description: 日志线程池，异步记日志
 * @author: wubing
 * @create: 2019-03-18 11:16
 */
@Slf4j
public class ThreadPoolService {

    private final ExecutorService exec = Ttl.wrap(new ThreadPoolExecutor(5 * Runtime.getRuntime().availableProcessors(), 100, 60L,
            TimeUnit.SECONDS, new LinkedBlockingQueue<>(200000)));


    private ThreadPoolService() {
    }

    private static class ThreadPoolServiceSingleton {
        private static ThreadPoolService instance = new ThreadPoolService();

    }

    /**
     * 获取线程池，单例
     *
     * @return
     */
    public static ThreadPoolService getInstance() {
        return ThreadPoolServiceSingleton.instance;
    }

    /**
     * 写日志
     */
    public void writeLog(LogLevelEnum levelEnum, String var1, Object var2) {
        exec.execute(() -> {
            switch (levelEnum) {
                case Info:
                    log.info(var1, var2);
                    break;
                case Warn:
                    log.warn(var1, var2);
                    break;
                case Debug:
                    log.debug(var1, var2);
                    break;
                case Error:
                    log.error(var1, var2);
                    break;
                default:
                    log.info(var1, var2);
                    break;
            }
        });
    }

    private final static String log_url = "https://ct.ctrip.com/corpgovernment/push/log";

    /**
     * 写携程日志
     */
    public void writeCtripLog(LogLevelEnum levelEnum, String title, String message, Map<String, String> tagMaps) {
        //发送日志到携程log
        exec.execute(() -> {
            JSONObject requestParam = new JSONObject();
            requestParam.put("levelCode", levelEnum == null ? LogLevelEnum.Info.getCode() : levelEnum.getCode());
            requestParam.put("title", title);
            requestParam.put("message", message);
            requestParam.put("tagMaps", tagMaps);
            CloseableHttpClient httpclient = HttpClients.createDefault();
            HttpPost httpPost = new HttpPost(log_url);
            try {
                RequestConfig config = RequestConfig.custom()
                        .setConnectTimeout(50000)
                        .setConnectionRequestTimeout(10000)
                        .setSocketTimeout(50000)
                        .build();
                httpPost.setConfig(config);
                StringEntity stringEntity = new StringEntity(JSONObject.toJSONString(requestParam),"UTF-8");
                stringEntity.setContentEncoding("UTF-8");
                stringEntity.setContentType("application/json");
                httpPost.setEntity(stringEntity);
                //response = HttpUtils.doPostJSON("Ctrip", "Ctrip", log_url, requestParam.toString());
                CloseableHttpResponse response = httpclient.execute(httpPost);
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                httpPost.releaseConnection();
            }
        });
    }


}
